/****************************************************************************
@FILENAME:	codec_uart.c
@FUNCTION:	decode/encode uart
@AUTHOR:	flege.zhang
@DATE:		2020.05.13
@COPYRIGHT(C) ZXW 2020
*****************************************************************************/

#include "app_select.h"
#include "codec_uart.h"
#include "uart.h"
#include "int.h"
#include "key_process.h"


#if(HW_DETECT_TYPE == DECODE_UART_TYPE)
str_decoded_uart decoded_uart;
uint8_t decode_uart_state = EN_UART_HEADER;
uint8_t data_index = 0x0;

extern str_key_info key_info;


void decode_uart_init(uint32_t baudrate_index)
{
    uart_init(baudrate_index);
	uart_set_baudrate(baudrate_index);
	int_enable_irq(INT_UART_EN_MASK);

	memset(&key_info,0x0,sizeof(str_key_info));
}

void decode_uart(uint8_t uart_data)
{
	uint8_t checksum = 0x0;
	uint8_t* p_data = (uint8_t*)&decoded_uart;

	switch(decode_uart_state)
	{
		case EN_UART_HEADER:
		{
			key_info.curr_key = 0x0;
			memset(p_data,0x00,sizeof(str_decoded_uart));
			
			if(AF_UART_HEADER == uart_data)
			{
				decoded_uart.header = uart_data;
				decode_uart_state++;
			}
			break;
		}
		case EN_UART_TYPE:
		{
			if(AF_UART_TYPE_CMD == uart_data)
			{
				decoded_uart.type = uart_data;
				decode_uart_state++;
			}
			else
			{
				decode_uart_state = EN_UART_HEADER;
#if LOG_MAJOR
				print("UART TYPE ERROR,\n");
#endif
			}
			break;
		}
		case EN_UART_LENGTH:
		{
			decoded_uart.length = uart_data;
			decode_uart_state++;
			data_index = 0x03;
			break;
		}
		case EN_UART_DATA:
		{
			p_data[data_index++] = uart_data;

			if(data_index == (decoded_uart.length + 0x03))
			{
				decode_uart_state++;
			}
			break;
		}
		case EN_UART_CHECKSUM:
		{
			for(uint8_t i = 0x1; i < (decoded_uart.length + 0x03); i++)
			{
				checksum += p_data[i];
			}
			
			if(checksum == uart_data)
			{
				decoded_uart.checksum = uart_data;
				decode_uart_state++;
			}
			else
			{
				decode_uart_state = EN_UART_HEADER;				
#if LOG_MAJOR
				print("UART SUM ERROR,\n");
#endif
			}
			break;
		}
		case EN_UART_END:
		{
			if(AF_UART_END == uart_data)
			{
				decoded_uart.end = uart_data;

				key_info.curr_key = (decoded_uart.opcode<<24)|(decoded_uart.group_index<<16)|(decoded_uart.para[0]<<8)|(decoded_uart.para[1]);
				key_info.para[0]  = decoded_uart.para[0];
				key_info.para[1]  = decoded_uart.para[1];
				key_info.para[2]  = decoded_uart.para[2];

				if(key_info.curr_key == key_info.last_key)
				{
					key_info.pressed_time++;
				}
				else
				{
					key_info.pressed_time = 0x01;
				}

				key_info.last_key = key_info.curr_key;
				key_info.handle_flag = 0x01;

				//TBD,do something
#if LOG_MAJOR
				print("UART:");
				for(uint8_t i = 0; i < sizeof(str_decoded_uart); i++)
				{
					print("%x ",p_data[i]);
				}
				print("\n");
#endif
			}
			
			decode_uart_state = EN_UART_HEADER;
			break;
		}
		default://data
		{
			break;
		}
	}
}
#endif

